import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as crypto from 'crypto';
import { throwHttpException1 } from '@/utils/nesjUtils';

import prismaClient from '@/config/prismaClient';
import { ILoginApiParams } from '../types';

// 校验入参
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    // 2、校验必填参数是否传递
    const requiredFields = [
      { name: '手机号', field: 'Phone' },
      { name: '密码', field: 'Password' },
    ];
    const errFields = requiredFields.filter((f) => {
      if (!!!req.body[f.field]) {
        return f;
      }
    });

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }

    next();
  }
}

// 校验手机号 是否存在
@Injectable()
class CheckPhoneIsExistMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const body = req.body as ILoginApiParams;
    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        Phone: body.Phone,
        IsDel: '0',
      },
    });
    if (baseUserList.length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！手机号不存在',
        data: '',
      });
    }
    // console.log('baseUserList', baseUserList);

    next();
  }
}

// 校验密码
@Injectable()
class CheckPasswordMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const body = req.body as ILoginApiParams;
    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        Phone: body.Phone,
        IsDel: '0',
      },
    });
    const formatPassword = crypto
      .createHash('sha256')
      .update(body.Password + Buffer.from('ddg', 'utf-8').toString('hex'))
      .digest('hex');
    if (formatPassword != baseUserList[0].Password) {
      throwHttpException1({
        state: '0',
        msg: '请检查密码是否正确！',
        data: '',
      });
    }
    next();
  }
}

// @Injectable()
// export class FirstMiddleware implements NestMiddleware {
//   async use(req: Request, res: Response, next: NextFunction) {
//     console.log('First middleware starts');
//     // 模拟异步操作
//     await new Promise((resolve) => setTimeout(resolve, 1000));
//     console.log('First middleware ends');
//     next(); // 调用 next() 以传递控制权
//   }
// }

// @Injectable()
// export class SecondMiddleware implements NestMiddleware {
//   use(req: Request, res: Response, next: NextFunction) {
//     console.log('Second middleware');
//     next(); // 调用 next()
//   }
// }

// @Injectable()
// export class ThirdMiddleware implements NestMiddleware {
//   async use(req: Request, res: Response, next: NextFunction) {
//     console.log('Third middleware starts');
//     // 模拟异步操作
//     await new Promise((resolve) => setTimeout(resolve, 2000));
//     console.log('Third middleware ends');
//     next(); // 调用 next()
//   }
// }

export default {
  CheckParamIsEmptyMiddleware,
  CheckPhoneIsExistMiddleware,
  CheckPasswordMiddleware,
  // FirstMiddleware,
  // SecondMiddleware,
  // ThirdMiddleware,
};
